import {
  createRouter,
  createWebHistory,
  createWebHashHistory,
} from "vue-router";
import { getStorage } from '@/utils/storage';
import { useMenusStore } from "@/stores/menus";
import { useUserStore } from "@/stores/user";

import LayOut from "@/components/layout.vue";

const routes = [
  {
    path: "/",
    redirect: "/login",
  },
  {
    path: "/login",
    name: "login",
    component: () => import("../views/login/login.vue"),
  },
  {
    path: "/home",
    // name: "home",
    component: LayOut,
    children: [
      {
        path: "/home",
        name: "home",
        component: () => import("../views/home/home.vue"),
      },
      {
        path: "/user",
        name: "user",
        component: () => import("../views/user/index.vue"),
      },
      {
        path: "/user-single",
        name: "user-single",
        component: () => import("../views/user-single/index.vue"),
      },
      {
        path: "/user-lasted",
        name: "user-lasted",
        component: () => import("../views/user-lasted/index.vue"),
      },
      {
        path: "/page1",
        name: "page1",
        component: () => import("../views/page1.vue"),
      },
      {
        path: "/page2",
        name: "page2",
        component: () => import("../views/page2.vue"),
      },
      {
        path: "/page3",
        name: "page3",
        component: () => import("@/views/page3.vue"),
      },
      {
        path: "/page4",
        name: "page4",
        component: () => import("@/views/page4.vue"),
      },
      {
        path: "/page5",
        name: "page5",
        component: () => import("@/views/page5.vue"),
      },
      {
        path: "/page6",
        name: "page6",
        component: () => import("@/views/page6.vue"),
      },
      {
        path: "/page7",
        name: "page7",
        component: () => import("@/views/page7.vue"),
      },
      {
        path: "/page8",
        name: "page8",
        component: () => import("@/views/page8.vue"),
      },
      {
        path: "/404",
        name: "noFind",
        component: () => import("@/views/noFind.vue"),
      },
      {
        path: "/:cathchAll(.*)",
        redirect: "/404",
      },
    ],
  },
];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
});

//设置路由守卫
const whiteList = ['/login', '/page2']
router.beforeEach((to, from, next) => {
  // console.log('to', to)
  // console.log('from', from)

  // 白名单直接放行
  if (whiteList.includes(to.path)) {
    next()
    return
  }

  const token = getStorage('token')
  if (!token) {
    next({path: '/login', query: {redirect: to.fullPath}})
    return
  }

  // 手动输入url 没有权限
  if (!getPermission(to)) {
    next({path: '/login'})
    return
  }


  next()
})

function getPermission(to) {
  const { menus } = useMenusStore()
  return menus.find(item => item.path == to.path)
}

export default router;
